﻿using EFCore.Sharding;
using Microsoft.Extensions.Hosting;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Wixa.IBusiness.Base_Manage;
using Wixa.Models.Base_Manage;
using Wixa.Models.DTO;
using Wixa.Util.DI;
using Wixa.Util.Extensions;
using Wixa.Util.Helper;
using Wixa.Util.Primitives;

namespace Wixa.Business.Base_Manage
{
    public class Base_UserBusiness : BaseBusiness<Base_User>, IBase_UserBusiness, ITransientDependency
    {
        private readonly string _solutionPath;
        public Base_UserBusiness(IDbAccessor db, IHostEnvironment env)
            : base(db)
        {
            _solutionPath = Directory.GetParent(env.ContentRootPath).ToString();
        }

        public List<Base_User> GetDataList()
        {
            return Db.GetIQueryable<Base_User>().ToList();
        }

        public void Build(BuildInputDTO input)
        {
            var areaName = input.AreaName;
            var tableNames = input.Tables;

            tableNames.ForEach(tableName =>
            {
                var tableColumnInfoList = SqlHelper.GetTableColumnInfoList(tableName, Db.ConnectionString);

                // 实体类名
                var entityName = tableName;

                //业务逻辑参数名
                var busName = $"{entityName.ToFirstLowerStr()}Bus";

                var selectOptionsList = new List<string>();
                var listColumnsList = new List<string>();
                var formColumnsList = new List<string>();

                tableColumnInfoList.ForEach(column =>
                {
                    //if (SqlHelper.DbTypeStr_To_CsharpType(column.Type) == typeof(string))
                    //{
                    listColumnsList.Add($"<el-table-column header-align=\"center\" align = \"left\" show-overflow-tooltip prop = \"{column.Name}\" label = \"{column.Description}\" /> ");
                    //}
                    formColumnsList.Add($"<el-form-item label=\"{ column.Description }\" prop=\"{column.Name }\"><el-input v-model = \"form.{column.Name}\" ></el-input></el-form-item>");

                });
                var templateFile = string.Empty;
                var savePath = string.Empty;
                var renderParamters = new Dictionary<string, string>
                    {
                        {$"%areaName%",areaName },
                        {$"%entityName%",entityName },
                        {$"%busName%",busName },
                        {$"%selectOptions%",string.Join("\r\n",selectOptionsList) },
                        {$"%listColumns%",string.Join("\r\n",listColumnsList) },
                        {$"%formColumns%",string.Join("\r\n",formColumnsList) }
                    };

                // 生成数据库实体类
                BuildEntity(tableColumnInfoList, tableName, areaName);

                // 生成业务层
                templateFile = "IBusiness.txt";
                savePath = Path.Combine(_solutionPath, "Wixa.IBusiness", areaName, $"I{entityName}Business.cs");
                WriteCode(renderParamters, templateFile, savePath);

                templateFile = "Business.txt";
                savePath = Path.Combine(_solutionPath, "Wixa.Business", areaName, $"{entityName}Business.cs");
                WriteCode(renderParamters, templateFile, savePath);

                templateFile = "Controller.txt";
                savePath = Path.Combine(_solutionPath, "Wixa.Api", "Controllers", areaName, $"{entityName}Controller.cs");
                WriteCode(renderParamters, templateFile, savePath);

                templateFile = "ListPage.txt";
                savePath = Path.Combine(_solutionPath, "Wixa.Web", "src", "views", areaName, entityName, "index.vue");
                WriteCode(renderParamters, templateFile, savePath);

                templateFile = "FormPage.txt";
                savePath = Path.Combine(_solutionPath, "Wixa.Web", "src", "views", areaName, entityName, "components", $"{entityName}Edit.vue");
                WriteCode(renderParamters, templateFile, savePath);

                templateFile = "PageApi.txt";
                savePath = Path.Combine(_solutionPath, "Wixa.Web", "src", "api", areaName, $"{entityName}.js");
                WriteCode(renderParamters, templateFile, savePath);
            });

        }

        private void BuildEntity(List<TableColumnInfo> tableInfo, string tableName, string areaName)
        {
            string nameSpace = $@"Wixa.Models.{areaName}";
            string filePath = Path.Combine(_solutionPath, "Wixa.Models", areaName, $"{tableName}.cs");

            SqlHelper.SaveEntityToFile(tableInfo, tableName, filePath, nameSpace);
        }

        private void WriteCode(Dictionary<string, string> paramters, string templateFileName, string savePath)
        {
            string content = File.ReadAllText(Path.Combine(_solutionPath, "Wixa.Api", "Templates", templateFileName));
            paramters.ForEach(aParamter =>
            {
                content = content.Replace(aParamter.Key, aParamter.Value);
            });
            var dir = Path.GetDirectoryName(savePath);
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }
            File.WriteAllText(savePath, content, Encoding.UTF8);
        }
    }
}
